package it.softphone.cmc.server.service;

import it.softphone.cmc.server.service.exception.CMCException;

import java.util.List;

import javax.persistence.EntityManager;

/**
 * 
 * @author bsorrentino
 *
 */
public interface EntityManagerBaseService {

	interface EMTask<T> {

		T exec( EntityManager em ) throws Exception ;
			
	}
	
	/**
	 * perform a query for generic entity
	 * 
	 * <pre>
	 * Example:
	 * 
	 * FROM JAVA
	 * ===============
	 * 
	 * java.util.Map<String,Object> paramMap = ...
	 * 
	 * service.find( 
  	 *   "SELECT r FROM TransactionEntity r WHERE r.userAgent=:paramName", paramMap, new QueryTask(){....} );
     *   
	 * FROM SCRIPT
	 * ===============
	 * 
	 * var jsObject = { ... };
	 * 
	 * EntityManager.find( 
  	 *   "SELECT r FROM TransactionEntity r WHERE r.userAgent=:paramName", toMap(jsObject), function(result){....} );
  	 *   
	 * var jsonString = "{ ... }";

	 * EntityManager.find( 
  	 *   "SELECT r FROM TransactionEntity r WHERE r.userAgent=:paramName", new JSONObject(jsonString), function(result){....} );
     *   
     * </pre>
     * <hr/>
     * <pre>
     * NOTE: parameter name convention
     *   
     * if param is a number 
     * prefix 'i' => integer
	 * prefix 'f' => float
     * prefix 'g' => double 
     * prefix 'l' => long 
     * prefix 'd' ==> conversion to date
	 *
	 *	if param is a date 
	 *	prefix 'd' => date
     *  prefix 't' => time
	 *  prefix 's' => timestamp  
     *
	 *	if param is a string 
	 *	prefix 'k' => convert string2Key
	 *
	 * <pre>
	 * 
	 * 
	 * @param sqlCommand command in JPA format
	 * @param paramMap could be null (no param), map, list, JSONObjet or JSONArray
	 * @param task 
	 * @throws CMCException
	 */
	<T> void find( String sqlCommand, Object paramMap, QueryTask<List<T>> task ) throws CMCException;
	
	/**
	 * 
	 * @param <T>
	 * @param sqlCommand
	 * @param paramMap
	 * @return null if not found
	 * @throws CMCException
	 */
	Object findSingle( String sqlCommand, Object paramMap ) throws CMCException;
	

	/**
	 * 
	 * @param method
	 * @param task
	 * @return
	 * @throws CMCException
	 */
	 <R> R execNewTransaction( String method, EMTask<R> task ) throws CMCException;
	
}
